const http = require('http')
const fs = require('fs')
const path = require('path')
const mime = require('mime')
const cache = {}

function send404(res) {
  res.writeHead(404, {'Content-Type': 'text/plain'})
  res.write('Error 404: resource not found.')
  res.end()
}

function sendFile(res, filePath, fileContents) {
  res.writeHead(
    200,
    {"content-type": mime.getType(path.basename(filePath))}
  )
  res.end(fileContents)
}

function serveStatic(res, cache, absPath) {
  // console.log('serve', absPath)
  if (cache[absPath]) {
    sendFile(res, absPath, cache[absPath])
  } else {
    const exits = fs.existsSync(absPath)
    if (exits) {
      fs.readFile(absPath, function (err, data) {
        if (err) {
          send404(res)
          return
        }
        cache[absPath] = data
        sendFile(res, absPath, data)
      })
    } else {
      send404(res)
    }
  }
}

const server = http.createServer(function (req, res) {
  let filePath
  if (req.url === '/') {
    filePath = 'public/index.html'
  } else {
    filePath = 'public' + req.url
  }
  const absPath = './' + filePath
  serveStatic(res, cache, absPath)
})

const port = 3003
server.listen(port, function () {
  console.log('Server listening on port ' + port)
})

const chatServer = require('./lib/chat_server')
chatServer.listen(server)
